package com.fengye.api.controller;

import com.fengye.common.annotation.RequestLimit;
import com.fengye.common.annotation.RateLimit;
import com.fengye.common.controller.BaseController;
import com.fengye.common.domain.MyPage;
import com.fengye.common.domain.ResponseResult;
import com.fengye.common.domain.dto.AddCommentDto;
import com.fengye.common.domain.entity.Comment;
import com.fengye.common.domain.vo.CommentVo;
import com.fengye.api.service.CommentService;
import com.fengye.common.utils.BeanCopyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * CommentController
 *
 * @author 枫叶fy
 * @description 评论
 * @since 2024/2/28 23:11
 */
@Api(tags = "评论模块")
@RestController
@RequestMapping("comment")
public class CommentController extends BaseController {
    @Autowired
    private CommentService commentService;

    /**
     * 获取评论列表
     *
     * @param articleId 文章id
     * @param pageNum   页码
     * @param pageSize  每页大小
     * @return 评论列表
     */
    @GetMapping("list")
    @ApiOperation("分页获取评论列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "articleId", value = "文章id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, dataType = "Integer", paramType = "query")
    })
    public ResponseResult<MyPage<CommentVo>> commentList(Long articleId, Integer pageNum, Integer pageSize) {
        MyPage<CommentVo> commentVoList = commentService.getCommentList(articleId, pageNum, pageSize);
        return ResponseResult.success(commentVoList);
    }

    /**
     * 添加评论（进行了限流）
     *
     * @param commentDto 评论信息实体类
     * @return 添加结果
     */
    @PostMapping("add")
    @ApiOperation("添加评论")
    @RateLimit(key = "addComment", permitsPerSecond = 20, timeout = 500, timeunit = TimeUnit.MILLISECONDS)
    @RequestLimit(maxCount = 1, interval = 5)
    public ResponseResult<Void> addComment(@RequestBody AddCommentDto commentDto) {
        Comment comment = BeanCopyUtils.copyBean(commentDto, Comment.class);
        commentService.addComment(comment);
        return ResponseResult.success();
    }
}
